/*使用多路复用实现并发服务器模型——服务端*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <stdbool.h>

//节点类型
typedef struct Node {
	int newfd;
	struct Node *next;

}link_node;

//初始化链表函数:创建头节点
link_node *init_link(void)
{
	link_node *head = (link_node *)malloc(sizeof(link_node));
	if (NULL == head) {
		perror("malloc");
		exit(1);
	}
	head->next = NULL;
	return head;
}

//在链表中插入节点
void head_insert(link_node *head, int newfd)
{
	link_node *pnode = (link_node *)malloc(sizeof(link_node));
	if (NULL == pnode) {
		perror("malloc");
		exit(1);
	} 
	pnode ->newfd = newfd;
	pnode->next = head->next;
	head->next = pnode;
}

//判断链表是否为空
bool isempty_linklist(link_node* head)
{
	if (head->next == NULL)
		return true;
	else
		return false;
}

//删除指定节点后的节点
void delete_node(link_node* pre)
{
	/*判断要删除的节点是否存在*/
	if (isempty_linklist(pre))
	{
		printf("该节点不存在，无法删除。\n");
		return;
	}
	
	/*删除节点*/
	link_node* temp = pre->next;
	pre->next = temp->next;
	free(temp);
}

//删除指定数据对应的节点
void delete(link_node* head,int data)
{
	link_node* p = head;
	while(p->next->newfd != data)
	{
		p = p->next;
		if (p == NULL)
		{
			printf("该数据对应节点不存在，无法删除。\n");
			return;
		}
	}
	
	delete_node(p);
}


int main(void)
{	
	int fd, newfd, id;
	int ret;
	int max; //保存最大的文件描述符
	link_node *head;
	link_node *temp; //保存遍历链表节点的指针
	char buf[50];
	char *p;
	
	head = init_link();//初始化链表
	
	//1.socket() 买电话
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		perror("socket");
		exit(1);
	}
	int on=1;
	setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); //重用端口号 on 设置为真
	//2.bind() 绑定电话卡
	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("192.168.104.89");
	server.sin_port = htons(12001);
	ret = bind(fd, (struct sockaddr *)&server, sizeof(server));
	if (ret == -1) {
		perror("bind");
		exit(1);
	}
	//3.listen() 监听
	listen(fd, 5); //不阻塞
	printf("tcp server have started...\n");

	//4.accept() 接听
	struct sockaddr_in client; //保存对方客户端的socket地址 (来电)
	socklen_t len = sizeof(client);
	
	//并发服务器模型框架代码

	//创建集合
	fd_set myset;
	max = fd;
	
	while (1) {
		//清空集合；
		FD_ZERO(&myset);
		//将 0 与 fd 添加到套接字集合；
		FD_SET(0, &myset);
		FD_SET(fd, &myset);
		//将链表中所有客户端文件描述符添加到套接字集合；
		temp = head->next;
		while (temp != NULL) {
			FD_SET(temp->newfd, &myset);
			temp = temp->next;
		}
		printf("pls input a string [fd:str]:");

		//调用select(max+1,); //监测
		select (max+1, &myset, NULL, NULL, NULL);

		//针对不同的fd做不同处理,分为三类

		//1.键盘输入
		if (FD_ISSET(0, &myset)) {
			bzero(buf, 50);			
			fgets(buf, 50, stdin);
			p = strtok(buf, ":");
			id = atoi(p); //字符串转整数
			p = strtok(NULL, ":");
			ret = send(id, p, strlen(p), 0);
			printf("send len= %d\n", ret);
			if (strncmp(p, "quit", 4) == 0) break;
		}


		//2.服务端和客户端建立连接
		if (FD_ISSET(fd, &myset)) {
			newfd = accept(fd, (struct sockaddr *)&client, &len);//没有连接请求就一直阻塞
			if (newfd == -1) {
				perror("accept");
				exit(1);
			}
			printf("connect success with client...\n");
			printf("客户端 fd= %d 上线!!!\n", newfd);
			max = newfd;
			//保存到链表
			head_insert(head, newfd);
		}

		//3.服务端和客户端通信
		temp = head->next;
		while (temp != NULL) 
		{
			if (FD_ISSET(temp->newfd, &myset)) {
				bzero(buf, 50);
				ret = read(temp->newfd, buf, sizeof(buf)); //阻塞
				printf("read client string: %s", buf);
				if (ret == 0) {
					printf("客户端 %d 掉线了!!!\n", temp->newfd);
					delete(head,temp->newfd);
					break;
				}
				if (ret < 0) {
					perror("read");
					continue;
				}
				if (strncmp(buf, "quit", 4) == 0) {
					printf("客户端 %d 下线了!!!\n", temp->newfd);
					delete(head,temp->newfd);
					break;
				}

			}
			temp = temp->next;
		}
		
	}
	
	//6.close() 挂电话
	close(newfd);
	close(fd);
	
	return 0;
}

